package com.iwhale.sequence.redisidx.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;

import java.util.Map;

public class ApplicationContextUtil {
    private static final Logger logger = LoggerFactory.getLogger(ApplicationContextUtil.class);

    private static ApplicationContext applicationContext;

    public static void setApplicationContext(ApplicationContext context) throws BeansException {
        applicationContext = context;
    }

    /**
     * 获取Spring容器上下文 @Title: getApplicationContext @return @throws
     */
    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    /**
     * 获得SpringBean实例 @Title: getBean @param beanName @return @throws
     */
    public static Object getBean(String beanName) {
        if (applicationContext == null) {
            return null;
        }
        return applicationContext.getBean(beanName);
    }

    /**
     * 根据beanName与类型返回Bean实例 @Title: getBean @param beanName @param requiredType @return @throws
     */
    public static <T> T getBean(String beanName, Class<T> requiredType) {
        if (applicationContext == null) {
            return null;
        }
        return applicationContext.getBean(beanName, requiredType);
    }

    /**
     * 根据一个指定的类型获取bean实例，如果有多个实例则会抛出异常
     * 
     * @Title: getBean
     * @param requiredType
     * @return
     */
    public static <T> T getBean(Class<T> requiredType) {
        if (applicationContext == null) {
            return null;
        }
        return applicationContext.getBean(requiredType);
    }

    /**
     * 根据类型获取所有的BEANS
     * 
     * @Title: getBean
     * @param requiredType
     * @return
     */
    public static <T> Map<String, T> getBeans(Class<T> requiredType) {
        if (applicationContext == null) {
            return null;
        }
        return applicationContext.getBeansOfType(requiredType);
    }

}
